package com.jiukuaidao.zhulin.module.address;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jiukuaidao.library.base.BaseActivity;
import com.jiukuaidao.library.base.BaseHolder;
import com.jiukuaidao.library.base.BaseXrecyclerViewAdapter;
import com.jiukuaidao.library.util.ToastUtil;
import com.jiukuaidao.library.widget.recyclerview.XRecyclerView;
import com.jiukuaidao.zhulin.AppContext;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.data.TaskProvider;
import com.jiukuaidao.zhulin.entity.ApiCityListInfo;
import com.jiukuaidao.zhulin.entity.ApiGeoCoderInfo;
import com.jiukuaidao.zhulin.entity.ApiHistoryAddressInfo;
import com.jiukuaidao.zhulin.module.address.bean.PreAddressBean;
import com.jiukuaidao.zhulin.module.address.contract.AddressManagerContract;
import com.jiukuaidao.zhulin.module.address.contract.CityListContract;
import com.jiukuaidao.zhulin.module.address.presenter.AddressMangerPresenter;
import com.jiukuaidao.zhulin.module.address.presenter.CityListPresenter;
import com.jiukuaidao.zhulin.util.AddressInfoUtil;
import com.jiukuaidao.zhulin.util.BDUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;

/**
 * Author : PaiTaSuo
 * Date : 2016/6/7
 * Description :
 */
public class ChangePositionActivity extends BaseActivity<AddressManagerContract.Presenter> implements AddressManagerContract.View, View.OnClickListener, CityListContract.View {
    @BindView((R.id.rl_title))
    RelativeLayout mRlTitle;
    @BindView(R.id.titile_left_imageview)
    ImageView mLeftImg;
    @BindView(R.id.titile_text)
    TextView mTitleText;
    @BindView(R.id.tv_sure)
    TextView mTvSure;
    @BindView(R.id.change_rl_add_address)
    RelativeLayout mAddAddress;
    @BindView(R.id.location_layout)
    RelativeLayout mLocationLayout;
    @BindView(R.id.location_address_textView)
    TextView mLocationAddress;
    @BindView(R.id.et_search)
    EditText mSearchEdt;
    @BindView(R.id.positon_recycle)
    XRecyclerView mRecycleView;
    private CityListTopPopup popupWindow;
    private ApiCityListInfo mCityListInfo;
    private CityListPresenter mCityPresenter;
    private BaseXrecyclerViewAdapter<ApiHistoryAddressInfo.AddressInfo> mBaseAdapter;
    public static ChangePositionActivity mInstance;
    private String mCityCode;
    private String mCurrentCity;
    private int mIndex = 1;
    private int mRefreshOrLoad = AddressManagerContract.REFRESH;

    @Override
    protected View getTargetView() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_change_position;
    }

    @Override
    protected void handleBundle(Bundle bundle) {
        mCityCode = bundle.getString("cityCode");
        mCurrentCity = bundle.getString("city");
    }

    @Override
    protected void init() {
        mInstance = this;
        EventBus.getDefault().register(this);
        mTitleText.setText(mCurrentCity);
        mCityPresenter = new CityListPresenter(TaskProvider.provideTasksRepository(this), this);
        mCityPresenter.loadData();
        new AddressMangerPresenter(TaskProvider.provideAddressRepository(this), this);
        mPresenter.start();

        setOnClickListener();
        mSearchEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(mSearchEdt.getText().toString().trim())) {
                    if (mTvSure.getVisibility() == View.GONE) {
                        mTvSure.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (mTvSure.getVisibility() == View.VISIBLE) {
                        mTvSure.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.titile_left_imageview:
                finish();
                break;
            case R.id.tv_sure:  //搜索
                if (mTitleText.getText().toString().equals(AppContext.getContext().getString(R.string.select_city))) {
                    ToastUtil.show(AppContext.getContext().getString(R.string.select_city), Toast.LENGTH_SHORT);
                    return;
                }
                bundle.putString("addressStr", mSearchEdt.getText().toString());
                bundle.putString("region", mTitleText.getText().toString());
                intentJump(SearchPlaceActivity.class, bundle);
                break;
            case R.id.location_layout:  // 定位
                BDUtils.start();
                break;
            case R.id.change_rl_add_address: // 新增地址
                bundle.putString("fromModel", "changeAddress");
                intentJump(AddAddressActivity.class, bundle);
                break;
            case R.id.titile_text:
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    return;
                }
                if (mCityListInfo == null) {
                    return;
                }
                popupWindow = new CityListTopPopup(ChangePositionActivity.this, mCityListInfo);
                popupWindow.showAsDropDown(mRlTitle);
                mLeftImg.setVisibility(View.GONE);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        mLeftImg.setVisibility(View.VISIBLE);
                    }
                });
                break;
            case R.id.rl_title:
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                break;
        }
    }

    public void setOnClickListener() {
        mLeftImg.setOnClickListener(this);
        mTvSure.setOnClickListener(this);
        mAddAddress.setOnClickListener(this);
        mLocationLayout.setOnClickListener(this);
        mTitleText.setOnClickListener(this);
        mRlTitle.setOnClickListener(this);
    }


    @Override
    public void getAddressInfo(final List<ApiHistoryAddressInfo.AddressInfo> shoppingAddressList) {
        if (null != mBaseAdapter) {
            mBaseAdapter.setData(shoppingAddressList);
            mBaseAdapter.notifyDataSetChanged();
        } else {
            initAddress(shoppingAddressList);
        }
    }

    public void initAddress(final List<ApiHistoryAddressInfo.AddressInfo> shoppingAddressList) {
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mRecycleView.setPullRefreshEnabled(false);
        mRecycleView.setLoadingMoreEnabled(false);
        mBaseAdapter = new BaseXrecyclerViewAdapter<ApiHistoryAddressInfo.AddressInfo>(this, R.layout.item_change_address, shoppingAddressList, mRecycleView) {

            @Override
            public void updateUI(BaseHolder holder, int position, ApiHistoryAddressInfo.AddressInfo data) {
                TextView address = holder.getView(R.id.tv_address_info);
                TextView mobile = holder.getView(R.id.tv_phone_info);
                TextView consignee = holder.getView(R.id.tv_name_info);
                address.setText(data.address);
                mobile.setText(data.mobile);
                consignee.setText(data.consignee);

            }

            @Override
            protected void onItemClick(BaseHolder holder, int position) {
                super.onItemClick(holder, position);

                // 点击我的收货地址 发送位置消息
                ApiHistoryAddressInfo.AddressInfo data = shoppingAddressList.get(position);
                //当前位置存入首选项
                AddressInfoUtil.cleanAddressInfo();
                PreAddressBean mAddressInfo = new PreAddressBean();
                mAddressInfo.longitude = data.longitude;
                mAddressInfo.latitude = data.latitude;
                mAddressInfo.city = data.city;
                mAddressInfo.cityCode = data.baiduCityCode;
                mAddressInfo.address = data.address;
                AddressInfoUtil.saveAddressInfo(mAddressInfo);
                EventBus.getDefault().post(data);
                finish();
            }

        };
        mRecycleView.setAdapter(mBaseAdapter);
    }

    @Override
    public void toast(String msg) {
        ToastUtil.show(msg, Toast.LENGTH_SHORT);
    }

    @Override
    public int index() {
        return mIndex;
    }

    @Override
    public int refreshOrLoad() {
        return mRefreshOrLoad;
    }


    @Override
    public void cityList(ApiCityListInfo cityListInfo) {
        mCityListInfo = cityListInfo;
    }

    @Override
    public String cityCode() {
        return mCityCode;
    }

    @Override
    public void setTitle(String title) {
        mTitleText.setText(title);
    }

    /**
     * @param cityList 切换城市
     */
    @Subscribe
    public void onEventTitleCity(ApiCityListInfo.CityList cityList) {
        mTitleText.setText(cityList.cityName);
        popupWindow.dismiss();
    }

    /**
     * @param apiGeoCoderInfo 定位当前城市
     */
    @Subscribe
    public void onEventLocationResult(ApiGeoCoderInfo apiGeoCoderInfo) {
        ToastUtil.show(apiGeoCoderInfo.result.sematic_description, Toast.LENGTH_SHORT);
        mLocationAddress.setText(apiGeoCoderInfo.result.sematic_description);
        finish();
    }


}
